package com.kx.kxpicture.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.exception.ThrowsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * url文件上传
 *
 * @author kuangxin
 * date 2025/9/3
 */
@Service
@Slf4j
public class UrlPictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowsUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");
        //校验url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }
        //校验url协议 http//https
        ThrowsUtils.throwIf(!(fileUrl.startsWith("http://")||fileUrl.startsWith("https://")),ErrorCode.PARAMS_ERROR,"url协议错误");
        //文件是否存在
        HttpResponse response=null;

        try {
            response= HttpUtil.createRequest(Method.HEAD,fileUrl).execute();
            if (response.getStatus()!= HttpStatus.HTTP_OK){
                return;
            }
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowsUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            String fileLength = response.header("Content-Length");
            if (StrUtil.isNotBlank(fileLength)){
                try {
                    long contentLength = Long.parseLong(fileLength);
                    final long TWO_MB = 2 * 1024 * 1024L;
                    ThrowsUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        }finally {
            if (response!=null){
                response.close();
            }
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl=(String)inputSource;
        return  FileUtil.mainName(fileUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl = (String)inputSource;
        HttpUtil.downloadFile(fileUrl,file);
    }
}
